#include "Computer.h"
#include <string.h>
#include <iostream>

using std::cout;
using std::endl;

Comupter::Comupter(const char *brand, float price)
: _brand(new char[strlen(brand) + 1]())//申请了空间
, _price(price)
{
    cout << "Comupter(const char *, float)" << endl;
    strcpy(_brand, brand);
}
#if 0
//编译器生成的拷贝构造函数
Comupter::Comupter(const Comupter &rhs)
: _brand(rhs._brand)//浅拷贝
, _price(rhs._price)
{
    cout << "Comupter(const Comupter &)" << endl;
}
#endif

Comupter::Comupter(const Comupter &rhs)
: _brand(new char[strlen(rhs._brand) + 1]())//深拷贝
, _price(rhs._price)
{
    cout << "Comupter(const Comupter &)" << endl;
    strcpy(_brand, rhs._brand);
}

#if 0
Comupter &Comupter::operator=(const Comupter &rhs)
{
    cout << "Comupter &operator=(const Comupter &)" << endl;
    _brand = rhs._brand;//浅拷贝
    _price = rhs._price;

    return *this;
}
#endif
//四步曲
Comupter &Comupter::operator=(const Comupter &rhs)
{
    cout << "Comupter &operator=(const Comupter &)" << endl;
    //左操作数    右操作数
    //如果是自己赋值给自己
    if(this != &rhs)//1、自复制
    {
        delete [] _brand;//2、释放左操作数
        _brand = nullptr;

        _brand = new char[strlen(rhs._brand) + 1]();//3、深拷贝
        strcpy(_brand, rhs._brand);

        _price = rhs._price;
    }

    return *this;//4、返回*this
}

void Comupter::setBrand(const char *brand)
{
    strcpy(_brand, brand);
}

void Comupter::setPrice(float price)
{
    _price = price;
}

void Comupter::print()
{
    if(_brand)
    {
        cout << "brand = " << _brand << endl;
    }
    cout << "price = " << _price << endl;
}

Comupter::~Comupter()
{
    cout << "~Comupter()" << endl;
    if(_brand)
    {
        delete [] _brand;
        _brand = nullptr;
    }
}
